const inquirer = require('inquirer');
const chalk = require('chalk');
// const Koa = require('koa');
// const cors = require('koa2-cors');
// const k2c = require('koa2-connect');
// const bodyParser = require('koa-bodyparser');
// const proxy = require('koa-better-http-proxy');
// const app = new Koa();
// app.use(bodyParser());
// app.use(cors());

const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware')
const cors = require('cors');
const app = express();

/**
 * 主入口
 */
function main(cmd){ 
        inquirer.prompt([
            {
                type:"input",
                message:"请输入要监听的端口号",
                name:'port',
                when: !cmd.port,
                default: '3001',
            },
            {
                type:"input",
                message:"请输入要转到的地址",
                name:'target',
                when: !cmd.target,
                default: 'http://127.0.0.1:3003/',
            },
        ]).then(answers=>{
            handleKoa(answers.port||cmd.port, answers.target||cmd.target)
        })
}

function handleKoa (port, target){
    app.use(cors({
        credentials: true, 
        optionsSuccessStatus: 200,
    }));
    app.use(/.(json|rjson)/,createProxyMiddleware({
        target: target, // 要转到的目录
        changeOrigin: true,
    }));
    app.listen(port,'localhost', function(){ //要劫持的接口; 第二个参数要写 localhost 或者 127.0.0.1
        console.log(chalk.green(`代理接口启动成功: \n http://127.0.0.1:${port}   将被转发到   ${target} `));
    })
}
module.exports = main;

/*
    遗留问题:
    1、主项目被监听不能写localhost？
        http://127.0.0.1:3013/index.html#/index/  可以被监听
        http://localhost:3013/index.html#/index/  不会被监听

    2、 如果前后端用同一个地址，要先启动前端项目，页面载入后，再开启代理项目 
        因为 先开启代理的话，代理会把监听到的前端资源404；页面载入后再开启监听，就只能监听到接口
 
 */